package com.chen.util;

import com.chen.bean.constants.WxConstants;
import com.chen.service.ChatService;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 定时任务
 */
@Component
@Slf4j
public class ScheduledTasks {

    @Autowired
    private ChatService chatService;

    @Autowired
    public RedisTemplate<String,Object> redisTemplate;

    // 使用 Cron 表达式，每5小时执行一次任务
  //  @Scheduled(cron = "0 0 0/5 * * ?")
  //  @PostConstruct
    public void syncMessageTask(){
        log.info("定时任务-redis同步mysql消息列表开始执行");
        Set<String> keys = new HashSet<>();

        // 定义扫描选项：匹配指定前缀
        ScanOptions options = ScanOptions.scanOptions().match(WxConstants.WX_HISTORY_MESSAGE_CACHE + "*").count(500).build();

        try (RedisConnection connection = redisTemplate.getConnectionFactory().getConnection()) {
            // 使用流式 API 进行键扫描
            connection.keyCommands().scan(options).forEachRemaining(key -> {
                if (keys.size() < 500) {
                    keys.add(new String(key));
                }
            });
        } catch (Exception e) {
            log.error("批量获取message redis key 异常",e);
        }
       keys.forEach(key -> chatService.syncMessage(key));
    }
    
}
